import { ref, useToast } from '@vueuse/core';
import { useCoze } from './useCoze';

export function useWorkflow() {
  const isRunning = ref(false);
  const result = ref(null);
  const error = ref(null);
  const { showToast } = useToast();
  const client = useCoze();

  const runWorkflow = async (workflowId, params = {}) => {
    isRunning.value = true;
    error.value = null;
    result.value = null;

    try {
      const response = await uni.request({
        url: 'https://api.coze.cn/v1/workflow/run',
        method: 'POST',
        header: {
          'Authorization': `Bearer ${client.config.token}`,
          'Content-Type': 'application/json'
        },
        data: {
          workflow_id: workflowId,
          parameters: params
        }
      });

      if (response.statusCode !== 200) {
        throw new Error(`HTTP错误: ${response.statusCode}`);
      }

      const data = response.data;
      if (data.code !== 0) {
        throw new Error(data.msg || '工作流执行失败');
      }

      result.value = data.data;
      showToast({
        title: '工作流执行成功',
        icon: 'success'
      });
      return data.data;
    } catch (err) {
      error.value = err.message || '工作流调用失败';
      showToast({
        title: error.value,
        icon: 'error'
      });
      console.error('工作流错误:', err);
      throw err;
    } finally {
      isRunning.value = false;
    }
  };

  return {
    isRunning,
    result,
    error,
    runWorkflow
  };
}